package com.haoyeteng.sxbd.modular.business.service.impl;

import com.haoyeteng.sxbd.modular.business.model.Address;
import com.haoyeteng.sxbd.core.util.ToolUtil;
import com.haoyeteng.sxbd.modular.business.dao.AddressMapper;
import com.haoyeteng.sxbd.modular.business.service.IAddressService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 用户地址表 服务实现类
 * </p>
 *
 * @author haoyeteng123
 * @since 2019-05-27
 */
@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements IAddressService {

	@Autowired
	private AddressMapper addressMapper;
	
	@Override
	@Transactional
	public void insertAddress(Address address) {
		if (address.getIfDefault() == 1) {
			Address addressTemp = addressMapper.selectOne(new Address(address.getUserId(),1));
			if(ToolUtil.isNotEmpty(addressTemp)) {
				addressTemp.setIfDefault(0);
				addressMapper.updateById(addressTemp);
			}
		}
		addressMapper.insert(address);
		
	}

	@Override
	@Transactional
	public void defaultById(Integer addressId) {
		Address address = addressMapper.selectById(addressId);
		
		Address addressTemp = addressMapper.selectOne(new Address(address.getUserId(), 1));
		if(ToolUtil.isNotEmpty(addressTemp)) {
			addressTemp.setIfDefault(0);
			addressMapper.updateById(addressTemp);
		}
		address.setIfDefault(1);
		addressMapper.updateById(address);
	}

	@Override
	@Transactional
	public void updateAddress(Address address) {
		if (address.getIfDefault() == 1) {
			Address addressTemp = addressMapper.selectOne(new Address(address.getUserId(),1));
			if(ToolUtil.isNotEmpty(addressTemp)) {
				addressTemp.setIfDefault(0);
				addressMapper.updateById(addressTemp);
			}
		}
		addressMapper.updateById(address);
		
	}

}
